package com.neuedu.service.impl;

import com.neuedu.pojo.Mail;
import com.neuedu.service.IMailService;
import com.neuedu.service.IRedisService;
import com.neuedu.util.JWTUtil;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

@Service
public class MailServiceImpl implements IMailService {
    @Resource
    JavaMailSender mailSender;
    @Resource
    IMailService mailService;
    @Resource
    IRedisService redisService;

    @Override
    public boolean send(Mail mail) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(mail.getFrom(), mail.getPersonal());
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(), true);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
        mailSender.send(message);
        return true;
    }

    @Override
    public boolean sendSecurityCode(String username, String email) {
        StringBuffer securityCode = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            securityCode.append((int) (Math.random() * 10));
        }
        Mail mail = new Mail();
        mail.setTo(email);
        mail.setSubject("燕大校友捐赠资金管理系统");
        mail.setContent("您请求的验证码是：" + securityCode + ",15分钟内有效，请尽快输入");
        if (mailService.send(mail)) {
            redisService.set(JWTUtil.SECURITYCODE_KEY + "-" + username, securityCode.toString(), 60 * 15);
            return true;
        } else {
            return false;
        }
    }
}
